package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Member;
import com.itheima.pojo.Result;
import com.itheima.utils.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    JedisPool jedisPool;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 校验用户是否登录
        // 获取请求头中携带的用户的token
        String token = request.getHeader("token");
        System.out.println(token);
        if (token == null) {
            noLogin(response);
            return false;
        }
        // 从redis 获取用户信息
        String redisToken = jedisPool.getResource().get(token);
        Member member = JSON.parseObject(redisToken, Member.class);
        if (member == null) {
            noLogin(response);
            return false;
        }
        return true;
    }

    private void noLogin(HttpServletResponse response) throws IOException {
        Result result = new Result(false, "没有登录", 401);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(result));
        writer.close();
    }
}
